package com.example.controller.web;

import cn.hutool.core.io.FileUtil;
import com.example.common.Result;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 文件相关操作接口
 */
@RestController
@RequestMapping("/files")
public class FileController {

//    // 表示本地磁盘文件的存储路径
//    private static final String filePath = System.getProperty("user.dir") + "/files/";
//
//    @Value("${fileBaseUrl}")
//    private String fileBaseUrl;
//
//    /**
//     * 文件上传
//     */
//    @PostMapping("/upload")
//    public Result upload(MultipartFile file) {
//        // 定义文件的唯一标识
//        String fileName = System.currentTimeMillis() + "-" + file.getOriginalFilename();
//        // 拼接完整的文件存储路径
//        String realFilePath = filePath + fileName;
//        try {
//            if (!FileUtil.isDirectory(filePath)) {
//                FileUtil.mkdir(filePath);
//            }
//            FileUtil.writeBytes(file.getBytes(), realFilePath);
//        } catch (IOException e) {
//            System.out.println("文件上传错误");
//        }
//        String url = fileBaseUrl + "/files/download/" + fileName;
//        return Result.success(url);
//    }
//
//    /**
//     * 文件下载
//     */
//    @GetMapping("/download/{fileName}")
//    public void download(@PathVariable String fileName, HttpServletResponse response) {
//        // 设置下载文件http响应头
//        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
//        // 拼接完整的文件存储路径
//        String realFilePath = filePath + fileName;
//        try {
//            // 通过文件的存储路径拿到文件字节数组
//            byte[] bytes = FileUtil.readBytes(realFilePath);
//            ServletOutputStream os = response.getOutputStream();
//            // 将文件字节数组写出到文件流
//            os.write(bytes);
//            os.flush();
//            os.close();
//        } catch (IOException e) {
//            System.out.println("文件下载错误");
//        }
//    }

    @Value("${tencent.cos.accessKey}")
    private String accessKey;

    @Value("${tencent.cos.secretKey}")
    private String secretKey;

    @Value("${tencent.cos.region}")
    private String region;

    @Value("${tencent.cos.bucket}")
    private String bucket;

    @Value("${fileBaseUrl}")
    private String fileBaseUrl;

    @PostMapping("/upload")
    public Result upload(MultipartFile file) {
        String fileName = System.currentTimeMillis() + "-" + file.getOriginalFilename();
        System.out.println(fileName);
        // 指定要上传到 COS 上对象键
        String key = "/avatar/" + fileName; // 根据需要设置路径
        try {
            // 初始化用户身份信息(secretId, secretKey)
            BasicCOSCredentials cred = new BasicCOSCredentials(accessKey, secretKey);
            // 设置bucket的区域
            ClientConfig clientConfig = new ClientConfig(new Region(region));
            // 生成cos客户端
            COSClient cosClient = new COSClient(cred, clientConfig);

            //创建ObjectMetadata
            ObjectMetadata metadata=new ObjectMetadata();
            metadata.setContentLength(file.getSize());
            // 创建PutObjectRequest对象
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, key, file.getInputStream(), metadata);
            // 上传文件
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            // 关闭客户端
            cosClient.shutdown();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("文件上传到COS失败");
        }
        String url = fileBaseUrl + key;
        System.out.println(url);
        return Result.success(url);
    }

    @PostMapping("/uploadWechat")
    public String uploadWechat(MultipartFile file) {
        String fileName = System.currentTimeMillis() + "-" + file.getOriginalFilename();
        System.out.println(fileName);
        // 指定要上传到 COS 上对象键
        String key = "/avatar/" + fileName; // 根据需要设置路径
        try {
            // 初始化用户身份信息(secretId, secretKey)
            BasicCOSCredentials cred = new BasicCOSCredentials(accessKey, secretKey);
            // 设置bucket的区域
            ClientConfig clientConfig = new ClientConfig(new Region(region));
            // 生成cos客户端
            COSClient cosClient = new COSClient(cred, clientConfig);

            //创建ObjectMetadata
            ObjectMetadata metadata=new ObjectMetadata();
            metadata.setContentLength(file.getSize());
            // 创建PutObjectRequest对象
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, key, file.getInputStream(), metadata);
            // 上传文件
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            // 关闭客户端
            cosClient.shutdown();
        } catch (Exception e) {
            e.printStackTrace();
            return "文件上传到COS失败";
        }
        String url = fileBaseUrl + key;
        System.out.println(url);
        return url;
    }

    @PostMapping("/uploadPost")
    public Result uploadPost(MultipartFile file) {
        String fileName = System.currentTimeMillis() + "-" + file.getOriginalFilename();
        System.out.println(fileName);
        // 指定要上传到 COS 上对象键
        String key = "/posts/" + fileName; // 根据需要设置路径
        try {
            // 初始化用户身份信息(secretId, secretKey)
            BasicCOSCredentials cred = new BasicCOSCredentials(accessKey, secretKey);
            // 设置bucket的区域
            ClientConfig clientConfig = new ClientConfig(new Region(region));
            // 生成cos客户端
            COSClient cosClient = new COSClient(cred, clientConfig);

            //创建ObjectMetadata
            ObjectMetadata metadata=new ObjectMetadata();
            metadata.setContentLength(file.getSize());
            // 创建PutObjectRequest对象
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, key, file.getInputStream(), metadata);
            // 上传文件
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            // 关闭客户端
            cosClient.shutdown();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("文件上传到COS失败");
        }
        String url = fileBaseUrl + key;
        return Result.success(url);
    }


}
